import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../services/adress_manger.dart';
import '../../models/adress_info_model.dart';
import '../view/adress_item_view.dart';
import '../../login/controller/adresss_pop_view.dart';
import '../../manger/global_config.dart';
import 'dart:io'; // 引入 dart:io 库
import '../../manger/user_manger.dart';
import '../../components/custom_dialog.dart';

class AddressPage extends StatefulWidget {
  const AddressPage({super.key});

  @override
  State<AddressPage> createState() => _AddressPageState();
}

class _AddressPageState extends State<AddressPage> {
  List<AdressInfo> adressInfo = [];
  final manager = AdressInfoManager();
  bool showAddressView = false;
  String urls = '';

  @override
  void initState() {
    super.initState();
    fetchAddressData();
  }

  Future<void> fetchAddressData() async {
    final success = await manager.loadInfoData();
    if (success.success) {
      setState(() {
        adressInfo = success.adressInfo ?? [];
      });
    } 
  }

  void showDeleteDialog(int index) {
    final localizations = AppLocalizations.of(context)!;
    showDialog(
      context: context,
      builder: (context) => CustomDialog(
        title: localizations.deleteAddress2,
        description: localizations.deleteAddress1,
        leftButtonText: localizations.cancel,
        rightButtonText: localizations.confirm,
        onLeftPressed: () => Navigator.pop(context),
        onRightPressed: () {
          Navigator.pop(context);
          deleteAddress(index);
        },
      ),
    );
    
  }

  void deleteAddress(int index) async{
    final success = await manager.deletteAddress(adressInfo[index].id.toString());
    if (success.success) {
      fetchAddressData();
    } 
  }

  void changeAddress(int index) {
    final String platformType = Platform.isIOS ? 'iOS' : 'Android';
    final adressId = adressInfo[index].id.toString();
    String url = "${UrlConfig.baseUrl}/appBilling2?terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&billingApp_id=$adressId";
    loadHtml(url);
  }

  void onAddAddress() {
    final String platformType = Platform.isIOS ? 'iOS' : 'Android';
    String url = "${UrlConfig.baseUrl}/appBilling2?terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}";
    loadHtml(url);
  }

  loadHtml(String url) {
    setState(() {
      urls = url;
      showAddressView = true;
    });
  }

  hideAddressView() {
    setState(() {
      showAddressView = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Scaffold(
          appBar: AppBar(
            title: Text(
              AppLocalizations.of(context)!.zhangdandizhi,
              style: const TextStyle(fontSize: 17),
            ),
          ),
          body: Column(
            children: [
              Expanded(
                child: ListView.builder(
                  padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                  itemCount: adressInfo.length + 1,
                  itemBuilder: (context, index) {
                    if (index == 0) {
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 12),
                        child: _AddAddressHeader(onTap: onAddAddress),
                      );
                    }
                    final item = adressInfo[index - 1];
                    return Padding(
                      padding: const EdgeInsets.only(bottom: 12),
                      child: AdressCell(
                        model: item,
                        onDelete: () => showDeleteDialog(index - 1),
                        onSet: () => changeAddress(index - 1),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),

        /// ⬇ Address 弹窗
        if (urls != "")
        AddresssPopView(
          url: urls,
          visible: showAddressView,
          onSaveSuccess: () {
            hideAddressView();
            fetchAddressData(); // 刷新地址数据
          },
          onDismiss: hideAddressView,
        ),
      ],
    );
  }
}

// -------------------------
// 新建地址按钮
// -------------------------
class _AddAddressHeader extends StatelessWidget {
  final VoidCallback onTap;

  const _AddAddressHeader({required this.onTap});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 70,
      padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 10),
      child: ElevatedButton.icon(
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.white,
          foregroundColor: const Color(0xFF4D7BFE), // titleBlueColor
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),
          ),
          elevation: 0,
          padding: const EdgeInsets.symmetric(horizontal: 16),
        ),
        onPressed: onTap,
        icon: const Icon(Icons.add),
        label: Text(
          AppLocalizations.of(context)!.newcreateAddress,
          style: const TextStyle(fontSize: 16),
        ),
      ),
    );
  }
}
